package com.gitee.huanminabc.demo.service.impl;

import com.gitee.huanminabc.demo.dal.mapper.WorkLogMapper;
import com.gitee.huanminabc.demo.dal.mapper.WorkMapper;
import com.gitee.huanminabc.demo.model.converter.WorkEntityToVoConverter;
import com.gitee.huanminabc.demo.model.entity.WorkEntity;
import com.gitee.huanminabc.demo.model.entity.WorkLogEntity;
import com.gitee.huanminabc.demo.model.vo.WorkVo;
import com.gitee.huanminabc.demo.service.WorkService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

@Service
public  class WorkServiceImpl implements WorkService {

    @Autowired
    private WorkMapper workMapper;

    @Autowired
    private WorkLogMapper workLogMapper;
    @Autowired
    private WorkEntityToVoConverter workEntityToVoConverter;


    @Override
    public Boolean save(WorkVo workVo) {
        if (Strings.isBlank(workVo.getWorkId())){
            workVo.setWorkId(UUID.randomUUID().toString());//工单id
        }

        WorkEntity workEntity = workEntityToVoConverter.fromVO(workVo);
        //查询数据库是否存在
        WorkEntity workEntity1 = workMapper.selectByWorkId(workVo.getWorkId());
        if (workEntity1 == null) { //不存在新增
            workMapper.insert(workEntity);
        }else{
            //修改
            workMapper.updateById(workEntity);
        }
        //保留记录
        WorkLogEntity workLogEntity = new WorkLogEntity();
        workLogEntity.setFieldsLog(workEntity.getFields());
        workLogEntity.setWorkId(workEntity.getWorkId());
        workLogEntity.setUpdateBy(workEntity.getOperator());
        workLogEntity.setUpdateTime(new Date());
        workLogMapper.insert(workLogEntity);
        return  true;
    }

    @Override
    public WorkLogEntity getWorkLog(String workId) {
        return workLogMapper.selectById(workId);
    }

    @Override
    public WorkEntity getWork(String workId) {
        return workMapper.selectByWorkId(workId);
    }
}
